//
//  LocationHistoryViewController.m
//  EZ Tracker
//
//  Created by FENGYL on 2016/11/29.
//  Copyright © 2016年 FENGYL. All rights reserved.
//

#import "LocationHistoryViewController.h"
#import "LocationHistoryDatePickerView.h"
#import "TotalDeviceSelectedViewController.h"
#import "LocationHistoryCoverView.h"
#import "UIView+XL.h"
#import "NetworkCommand.h"
#import "UserModel.h"
#import "KCAnnotation.h"
#import "WGS84TOGCJ02.h"

#import <SVProgressHUD.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface LocationHistoryViewController ()<MKMapViewDelegate>

@property (strong , nonatomic) CLLocationManager * locationManager;
@property (strong , nonatomic) MKMapView *mapView;
@property (strong , nonatomic) LocationHistoryDatePickerView * locationHistoryDatePickerView;
@property (strong, nonatomic) UserModel *userModel;
@property (strong, nonatomic) NSArray *pointArray;

@property (weak, nonatomic) IBOutlet UIView *searchVIew;
@property (weak, nonatomic) IBOutlet UIButton *dateButton;
@property (weak, nonatomic) IBOutlet UIButton *startingTimeButton;
@property (weak, nonatomic) IBOutlet UIButton *endTimeButton;
@property (strong , nonatomic) LocationHistoryCoverView * coverView;
@property (weak, nonatomic) IBOutlet UIView *timeLineView;
@property (weak, nonatomic) IBOutlet UILabel *deviceNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *pointTimeLabel;
@property (weak, nonatomic) IBOutlet UISlider *timeSlider;


@end

@implementation LocationHistoryViewController

-(NSArray *)pointArray{
    
    if (!_pointArray) {
        _pointArray = [NSArray array];
    }
    return _pointArray;
}

-(UserModel *)userModel{
    
    if (!_userModel) {
        _userModel = [[UserModel alloc]init];
    }
    return _userModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化地图
    [self locationEnable];
    [self setMap];
    
    //阴影
    [self setViewShadow:self.searchVIew];
    [self setViewShadow:self.timeLineView];
    
    //name
    [self.deviceNameLabel setText:self.userModel.selectedDeviceSerialNumber];
    
    //coverView
    self.coverView = [[LocationHistoryCoverView alloc]initWithLocationHistoryCoverView];
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self.coverView];
    
    __block LocationHistoryViewController * safeSelf = self;
    self.coverView.removeDatePickerView = ^(){
      
        safeSelf.coverView.alpha = 0;
        
        [safeSelf.locationHistoryDatePickerView removeFromSuperview];
        
    };
    
    //设置当前日期
    
    NSDate * date = [NSDate date];
    
    NSDateFormatter * dateformatter = [[NSDateFormatter alloc]init];
    [dateformatter setDateFormat:@"dd/MM/yyyy"];
    NSString * datestring = [dateformatter stringFromDate:date];
    
    [self.dateButton setTitle:datestring forState:UIControlStateNormal];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark View阴影效果
-(void)setViewShadow:(UIView *)sender{
    
    sender.layer.shadowColor = [UIColor blackColor].CGColor;
    
    sender.layer.shadowOffset = CGSizeMake(2, 2);
    
    sender.layer.shadowOpacity = 0.4;
    
    sender.layer.shadowRadius = 4;
    
}

#pragma mark 初始化地图

-(void)setMap{
    
    self.mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    
    [self.view addSubview:self.mapView];
    
    [self.view sendSubviewToBack:self.mapView];
    
    self.mapView.delegate = self;
    
//    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    
    self.mapView.mapType = MKMapTypeStandard;
    
    
    
}

#pragma mark 判断是否有权限
-(void)locationEnable{
    
    self.locationManager = [[CLLocationManager alloc] init];
    
    //是否具有定位权限
    int status=[CLLocationManager authorizationStatus];
    
    //请求权限
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8)
    {
        //由于IOS8中定位的授权机制改变 需要进行手动授权
        
        //获取授权认证
        [self.locationManager requestAlwaysAuthorization];
    }
    
    if (status < 3 || ![CLLocationManager locationServicesEnabled]){
        
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"The user is not allowed to turn on the location service" message:@"Please turn on location service" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction * confirmAction = [UIAlertAction actionWithTitle:@"Setting" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url])
            {
                [[UIApplication sharedApplication] openURL:url];
                
            }
            
        }];
        
        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertController addAction:confirmAction];
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        
        
        
    }
    
}

#pragma mark 日期选择
- (IBAction)selectEndTime:(id)sender {
    
    self.coverView.alpha = 1;
    
    self.locationHistoryDatePickerView = [[LocationHistoryDatePickerView alloc]initWithLocationHistoryDatePickerViewStyle:NO dateString:self.endTimeButton.titleLabel.text];
    
    __block LocationHistoryViewController * safeSelf = self;
    
    //去掉datePickerView
    self.locationHistoryDatePickerView.removeDatePickerView = ^{
        
        safeSelf.coverView.alpha = 0;
        
        [safeSelf.locationHistoryDatePickerView removeFromSuperview];
        
    };
    
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    
    [window addSubview:self.locationHistoryDatePickerView];
    
    
    //更改日期
    self.locationHistoryDatePickerView.selectDate = ^(NSDate * date){
        
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm"];
        NSString *dateString = [dateFormatter stringFromDate:date];
        
        [safeSelf.endTimeButton setTitle:dateString forState:UIControlStateNormal];
        
        safeSelf.locationHistoryDatePickerView.removeDatePickerView();
        
    };
    
}


- (IBAction)selectStartingTime:(id)sender {
    
    self.coverView.alpha = 1;
    
    self.locationHistoryDatePickerView = [[LocationHistoryDatePickerView alloc]initWithLocationHistoryDatePickerViewStyle:NO dateString:self.startingTimeButton.titleLabel.text];
    
    __block LocationHistoryViewController * safeSelf = self;
    
    self.locationHistoryDatePickerView.removeDatePickerView = ^{
        
        safeSelf.coverView.alpha = 0;
        
        [safeSelf.locationHistoryDatePickerView removeFromSuperview];
        
    };
    
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    
    [window addSubview:self.locationHistoryDatePickerView];
    
    self.locationHistoryDatePickerView.selectDate = ^(NSDate * date){
        
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm"];
        NSString *dateString = [dateFormatter stringFromDate:date];
        
        [safeSelf.startingTimeButton setTitle:dateString forState:UIControlStateNormal];
        
        safeSelf.locationHistoryDatePickerView.removeDatePickerView();
        
    };
    
}

- (IBAction)selectDate:(id)sender {
    
    self.coverView.alpha = 1;
    
    self.locationHistoryDatePickerView = [[LocationHistoryDatePickerView alloc]initWithLocationHistoryDatePickerViewStyle:YES dateString:self.dateButton.titleLabel.text];
    
    __block LocationHistoryViewController * safeSelf = self;
    
    self.locationHistoryDatePickerView.removeDatePickerView = ^{
        
        safeSelf.coverView.alpha = 0;
        
        [safeSelf.locationHistoryDatePickerView removeFromSuperview];
        
    };
    
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    
    [window addSubview:self.locationHistoryDatePickerView];
    
    self.locationHistoryDatePickerView.selectDate = ^(NSDate * date){
        
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd/MM/yyyy"];
        NSString *dateString = [dateFormatter stringFromDate:date];
        
        [safeSelf.dateButton setTitle:dateString forState:UIControlStateNormal];
        
        safeSelf.coverView.alpha = 0;
        
        safeSelf.locationHistoryDatePickerView.removeDatePickerView();
        
    };
    
}

#pragma mark 查找轨迹
- (IBAction)touchSearchButton:(id)sender {
    
    NSString *startTime = [NSString stringWithFormat:@"%@ %@:00",self.dateButton.titleLabel.text,self.startingTimeButton.titleLabel.text];
    
    NSString *endTime = [NSString stringWithFormat:@"%@ %@:00",self.dateButton.titleLabel.text,self.endTimeButton.titleLabel.text];
    
    [SVProgressHUD showWithStatus:@"Loading..."];
    
    [NetworkCommand getHistoryTrackPoiDataByTimeForStartTime:startTime EndTime:endTime Success:^(NSArray *responseObject) {
        
        //判断有无数据
        if (responseObject.count > 0) {
            
            if ([[responseObject firstObject] class] == [NSNull class]) {
                
                [SVProgressHUD showErrorWithStatus:@"No data"];
                
                [SVProgressHUD dismissWithDelay:1];
                
                return;
                
            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"No Data"];
            
            [SVProgressHUD dismissWithDelay:1];
            
            return;
            
        }
        
        
        
        self.timeLineView.hidden = NO;
        
//        self.pointArray = responseObject;
        
        [self.mapView removeOverlays:self.mapView.overlays];
        
        [self.mapView removeAnnotations:self.mapView.annotations];
        
        for (int i = 0; i < responseObject.count; i++) {
            
            NSDictionary *dict = responseObject[i];
            
            if (i == 0) {
                
                [self addAnnotationForResponseObject:dict IsFitst:YES];
                
                NSDate *date = [NetworkCommand TimestampChangeDate:[dict valueForKey:NC_GPSTIME]];
                
                [self refreshDateForDate:date];
                
                
                 
            }else{
                
                [self addAnnotationForResponseObject:dict IsFitst:NO];
                
            }
            
            
            
        }
        
        [self addTwoPointLinkForResponse:responseObject];
        
        [SVProgressHUD dismiss];
        
    } failure:^{
        
        [SVProgressHUD showErrorWithStatus:@"Failure"];
        
        [SVProgressHUD dismissWithDelay:1];
        
    }];
    
}

#pragma mark 刷新进度条和时间label
-(void)refreshDateForDate:(NSDate *)date{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"dd/MM/yyyy HH:mm"];
    
    NSString *timeSting = [formatter stringFromDate:date];
    
    [self.pointTimeLabel setText:timeSting];
    
    //小时
    [formatter setDateFormat:@"HH"];
    
    NSString *hourString = [formatter stringFromDate:date];
    
    int hour = [hourString intValue];
    
    //分钟
    [formatter setDateFormat:@"mm"];
    
    NSString *minuteString = [formatter stringFromDate:date];
    
    int minute = [minuteString intValue];
    
    //总秒数
    int totalSecond = hour * 60 + minute;
    
    self.timeSlider.value = totalSecond/(24.0 * 60.0);
    
}

#pragma mark 返回查找轨迹
- (IBAction)backToSearchView:(id)sender {
    
    self.timeLineView.hidden = YES;
    
}

#pragma mark 添加大头针
-(void)addAnnotationForResponseObject:(NSDictionary *)responseObjectDictionary IsFitst:(BOOL)isFirst{
    
    NSString *serialNumber = self.userModel.selectedDeviceSerialNumber;
    
    NSDictionary *dict = responseObjectDictionary;
    
    NSNumber *latitude = [dict valueForKey:NC_LAT];
    
    NSNumber *longitude = [dict valueForKey:NC_LNG];
    
    
    
    
    if ([latitude floatValue] != 0 && [longitude floatValue] != 0) {
        
        
        //获取准确坐标
        CLLocationCoordinate2D location = CLLocationCoordinate2DMake([latitude floatValue], [longitude floatValue]);
        
        
        CLLocationCoordinate2D fixLocation;
        
        NSLog(@"latitude %f longitude %f",location.latitude,location.longitude);
        
        if (![WGS84TOGCJ02 isLocationOutOfChina:location]) {
            
            fixLocation = [WGS84TOGCJ02 transformFromWGSToGCJ2:location];
            
        }else{
            
            fixLocation = location;
            
        }
        
        
        
        KCAnnotation *annotation = [[KCAnnotation alloc]init];
        
        annotation.title = [dict valueForKey:NC_SERIAL_NUMBER];
        
        annotation.gpsTime = [dict valueForKey:NC_GPSTIME];
        
        annotation.coordinate = fixLocation;
        
        
        if (!isFirst) {
            
            annotation.isFirstPoint = NO;
            
            annotation.image = [UIImage imageNamed:@"ic_dot_marker_2"];
            
        }else{
            
            annotation.isFirstPoint = YES;
            
            //合成图片
            NSInteger powerValue = [[dict valueForKey:NC_POWER_VALUE] integerValue];
            
            UIImage *powerImage;
            
            if (powerValue >= 70) {
                
                powerImage = [UIImage imageNamed:@"ic_power_full"];
                
            }else if (powerValue < 70 && powerValue >= 20){
                
                powerImage = [UIImage imageNamed:@"ic_power_medium"];
                
            }else{
                
                powerImage = [UIImage imageNamed:@"ic_power_low"];
                
            }
            
            annotation.image = [self addImage:[UIImage imageNamed:@"ic_track_marker_boy_2"] toImage:[UIImage imageNamed:@"ic_tracker_useractivity_yuan_2"] powerImage:powerImage powerValue:powerValue];
            
        }
        
        
        
        [_mapView addAnnotation:annotation];
        
        NSLog(@"add annotation %@",serialNumber);
        
        
        if (annotation.isFirstPoint) {
            
            double eyeAltitude;
            
            if (_mapView.camera.altitude > STATIC_ALTITUDE) {
                
                eyeAltitude = STATIC_ALTITUDE;
                
            }else{
                
                eyeAltitude = _mapView.camera.altitude;
                
            }
            
            //移动到大头针位置
            MKMapCamera *mkMapCamera = [MKMapCamera cameraLookingAtCenterCoordinate:fixLocation fromEyeCoordinate:fixLocation eyeAltitude:eyeAltitude];
            
            if (fabs(fixLocation.latitude) <= 90 && fabs(fixLocation.longitude) < 180 ) {
                [_mapView setCamera:mkMapCamera animated:NO];
            }
            
//            [_mapView setCamera:mkMapCamera animated:NO];
            
            NSLog(@"altitude %f",_mapView.camera.altitude);
            
        }
        
        
        
    }else{
        
        [SVProgressHUD showErrorWithStatus:@"No data"];
        
        [SVProgressHUD dismissWithDelay:1];
        
        
        
    }
    
    
    
}

#pragma mark 合成图片
- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 powerImage:(UIImage *)powerImage powerValue:(NSInteger)powerValue{
    
    //大头针
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(image1.size.width, image1.size.height * 2), NO, 0.0);
    
    // Draw image1
    [image1 drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)];
    
    // Draw image2
    [image2 drawInRect:CGRectMake(2, 2, image1.size.width - 4, image1.size.width - 4)];
    
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return resultingImage;
}

#pragma mark - 地图控件代理方法
#pragma mark 显示大头针时调用，注意方法中的annotation参数是即将显示的大头针对象
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    //由于当前位置的标注也是一个大头针，所以此时需要判断，此代理方法返回nil使用默认大头针视图
    if ([annotation isKindOfClass:[KCAnnotation class]]) {
        
        KCAnnotation *kcAnnotation = (KCAnnotation *)annotation;
        
        static NSString *key1=@"AnnotationKey1";
        MKAnnotationView *annotationView=[_mapView dequeueReusableAnnotationViewWithIdentifier:key1];
        //如果缓存池中不存在则新建
        if (!annotationView) {
            annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key1];
            annotationView.canShowCallout=true;//允许交互点击
            annotationView.calloutOffset=CGPointMake(0, 0);//定义详情视图偏移量
            annotationView.canShowCallout = NO;
            
            if (kcAnnotation.isFirstPoint) {
                
                annotationView.layer.anchorPoint = CGPointMake(0.5, 0.5);
                
            }
            
            annotationView.leftCalloutAccessoryView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_classify_cafe.png"]];//定义详情左侧视图
        }
        
        //修改大头针视图
        //重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的，位置是放到缓存池时的位置)
        annotationView.annotation=annotation;
        annotationView.image=((KCAnnotation *)annotation).image;//设置大头针视图的图片
        
        
        return annotationView;
    }else {
        return nil;
    }
}


#pragma mark 添加路线
-(void)addTwoPointLinkForResponse:(NSArray *)responseObject{
    
    NSInteger count = responseObject.count;
    
    CLLocationCoordinate2D coods[count];
    
    for (int i = 0; i < count; i++) {
        
        if (responseObject.count <= 1) {
            
            return;
            
        }
        
        
        
        NSDictionary *dict = responseObject[i];
        
        NSNumber *latitude = [dict valueForKey:NC_LAT];
        NSNumber *longitude = [dict valueForKey:NC_LNG];
        
        CLLocationCoordinate2D locationCoordinate2D = CLLocationCoordinate2DMake([latitude doubleValue], [longitude doubleValue]);
        
        if (![WGS84TOGCJ02 isLocationOutOfChina:locationCoordinate2D]) {
            
            locationCoordinate2D = [WGS84TOGCJ02 transformFromWGSToGCJ2:locationCoordinate2D];
            
            
            
        }
        
        
        
        coods[i] = locationCoordinate2D;
        
        
        
    }
    
    MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coods count:count];
    
    [self.mapView addOverlay:polyline];
    
}

#pragma mark 线属性
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay{
    
    //绘制线条
    if ([overlay isKindOfClass:[MKPolyline class]])
    {
        MKPolylineRenderer *polylineRender = [[MKPolylineRenderer alloc]initWithPolyline:overlay];
        
        polylineRender.strokeColor = [UIColor redColor];
        
        polylineRender.lineWidth = 3;
        
        return polylineRender;
    }
    
    return nil;
    
}

//- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
//{
//    //绘制线条
//    if ([overlay isKindOfClass:[MKPolyline class]])
//    {
//        MKPolylineRenderer *polylineRender = [[MKPolylineRenderer alloc]initWithPolyline:overlay];
//        
//        polylineRender.strokeColor = [UIColor redColor];
//        
//        polylineRender.lineWidth = 3;
//        
//        return (MKOverlayView *)polylineRender;
//    }
//    
//    return nil;
//}

#pragma mark 选中大头针时触发
//点击一般的大头针KCAnnotation时添加一个大头针作为所点大头针的弹出详情视图
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{
    
    KCAnnotation *annotation = view.annotation;
    
    if ([view.annotation isKindOfClass:[KCAnnotation class]]) {
        
        NSString *dateString = [annotation.gpsTime stringValue];
        
        NSDate *date = [NetworkCommand TimestampChangeDate:dateString];
        
        [self refreshDateForDate:date];
        
        
    }
}

#pragma mark 点击列表按钮
- (IBAction)toucTotalDeviceButton:(id)sender {
    
    TotalDeviceSelectedViewController *totalDeviceSelectedViewController = [[TotalDeviceSelectedViewController alloc]init];
    
    [self.navigationController showViewController:totalDeviceSelectedViewController sender:nil];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
